com.mahees.jobTracker.views.JobPageView = com.mahees.backbone.View.BasicView.extend({

	tagName : 'tr',

	templateIdentifier : '#item-template',

	events : {
		'click .deleteJobSite' : 'destroy',
		'click .saveJobSite' : 'saveJobSite',
		'change input' : 'updateModel'
	},

	saveJobSite : function(e) {
		e.preventDefault();
		// TODO: set calls validate right, but save doesnt
		this.model.isValid() && this.model.save();
		return false;
	},

	afterRender : function() {
		$(this.el).removeClass('error');
	}
});

com.mahees.jobTracker.views.JobPageReadOnlyView = Backbone.View.extend({

	tagName : 'tr',

	templateIdentifier : '#item-readonly-template',

	events : {
		'click .deleteJobSite' : 'destroy'
	},

	initialize : function() {
		_.bindAll(this, 'render', 'unrender', 'destroy');

		this.model.bind('change', this.render);
		this.model.bind('destroy', this.unrender);
	},

	unrender : function() {
		$(this.el).remove();
	},

	destroy : function(e) {
		e.preventDefault();
		this.model.destroy();
		return false;
	},

	render : function() {
		var html = _.template($(this.templateIdentifier).html(), this.model.toJSON())
		$(this.el).html(html);
		
		if (this.model.previous('pageLastChanged') != this.model.get('pageLastChanged')) {
			$(this.el).addClass('highlight');
		}

		return this;
	}
});

com.mahees.jobTracker.views.ReviewedJobPagesCollectionView = com.mahees.backbone.View.BasicListView.extend({
	el : $('#reviewedJobPagesContainer'),

	refModelView : com.mahees.jobTracker.views.JobPageReadOnlyView,

	events : {},

	beforeRender : function() {
		$(this.el).html($('#job-page-readonly-table-header-static-template').html());
	}
});

com.mahees.jobTracker.views.JobPagesCollectionView = com.mahees.backbone.View.BasicListView.extend({
	el : $('#jobPages'),

	refModelView : com.mahees.jobTracker.views.JobPageView,

	events : {},

	beforeRender : function() {
		$(this.el).html($('#job-page-table-header-static-template').html());
	}

});

com.mahees.jobTracker.views.LoginRegisterPageView = Backbone.View.extend({

	el : $('#login-register-page'),

	events : {
		'click #signOnButton' : 'clickSignOnButton',
		'click #registerButton' : 'clickRegisterButton'
	},

	initialize : function() {

	},

	clickSignOnButton : function(e) {
		var self = this;
		// does post to resource to authenticate user credentials
		$.post('../user/login.json', {
			email : $('[name=email]', this.el).val()
		}, function(res) {
			window.authenticatedOnInit = true
			self.clearForm();
			self.options.eventBus.trigger('navigate', '');
		}).error(function(res) {
			var parsedRes = JSON.parse(res.responseText);

			var errorNode = self.generateErrorNode(parsedRes)

			$('#signOnMessage', self.el).html(errorNode)
		});
	},

	generateErrorNode : function(errorJson) {
		var errorsContainer = $(document.createElement('ul'));

		(!errorJson.errorMessage) || errorsContainer.append('<li>' + errorJson.errorMessage + '</li>');

		_.each(errorJson.fieldErrors, function(err) {
			$('[name=' + err.field + ']', self.el).addClass('error');

			var html = _.template($('#error-item-template').html(), err);
			errorsContainer.append(html);
		});

		return errorsContainer;
	},

	clickRegisterButton : function(e) {
		// register user
		var self = this;

		$.post('../user/register.json', {
			email : $('[name=email]', this.el).val()
		}, function(res) {
			var text = 'Registered successfully, try signing on with ' + res.email
			$('#signOnMessage', self.el).html(text)
		}).error(function(res) {
			var parsedRes = JSON.parse(res.responseText);

			var errorNode = self.generateErrorNode(parsedRes)

			$('#signOnMessage', self.el).html(errorNode)
		});
	},

	clearForm : function() {
		$('input[type=text]', this.el).val('').removeClass('error')
		$('#signOnMessage', this.el).html('')
	}
});

com.mahees.jobTracker.views.JobSitesPageView = Backbone.View.extend({
	el : $('#jobsites-page'),

	events : {
		'click .addJobPage' : 'addNewJobSite',
		'click .updateAllJobSites' : 'updateAllJobSites',
		'click .logout' : 'logout'
	},

	initialize : function() {
		_.bindAll(this, 'updateAllJobSites', 'logout');

		_.extend(this, Backbone.Events);
	},

	logout : function(e) {
		var self = this;

		e.preventDefault();
		$.get('../user/logout.json', function(resp) {
			window.authenticatedOnInit = false
			self.options.eventBus.trigger('navigate', 'login');
		});
		return false;
	},

	updateAllJobSites : function(e) {
		self = this;
		e.preventDefault();
		$.get('../jobSite/refreshJobSites', function(resp) {
			self.trigger('updateReviewedModels', resp);
		});

		return false;
	},

	addNewJobSite : function(e) {
		e.preventDefault();
		this.trigger('addNewJobSite');
		return false;
	}

});

com.mahees.jobTracker.ApplicationRouter = Backbone.Router.extend({
	routes : {
		'' : 'index',
		'login' : 'login'
	},

	initialize : function() {
		_.bindAll(this, 'login', 'index');

		this.eventBus = new com.mahees.jobTracker.EventBus();
		this.eventBus.bind('navigate', function(url) {
			this.navigate(url, true)
		}, this);

		// page level views
		this.loginRegisterPageView = new com.mahees.jobTracker.views.LoginRegisterPageView({
			eventBus : this.eventBus
		});

		this.jobSitesPageView = new com.mahees.jobTracker.views.JobSitesPageView({
			eventBus : this.eventBus
		});

		// init collections
		this.jobPagesCollection = new com.mahees.jobTracker.collections.JobPages;

		var reviewedJobSitesCollection = new com.mahees.jobTracker.collections.JobPages;
		var pendingJobSitesCollection = new com.mahees.jobTracker.collections.JobPages;

		this.jobPagesCollectionView = new com.mahees.jobTracker.views.JobPagesCollectionView({
			collection : pendingJobSitesCollection,
			eventBus : this.eventBus
		});

		new com.mahees.jobTracker.views.ReviewedJobPagesCollectionView({
			collection : reviewedJobSitesCollection
		});

		// bindings
		this.jobSitesPageView.bind('addNewJobSite', function(args) {
			pendingJobSitesCollection.add(new pendingJobSitesCollection.model);
		});

		this.jobSitesPageView.bind('updateReviewedModels', function(jsonCollection) {
			_.each(jsonCollection, function(jsonModel) {
				var foundModel = _.find(reviewedJobSitesCollection.models, function(model) {
					return model.get('id') == jsonModel.id
				});
				
				var changes = jsonModel.added.length + jsonModel.removed.length 
				
				foundModel && foundModel.set({
					pageLastChanged : jsonModel.pageLastChanged,
					added : _.map(jsonModel.added, function(obj) { return obj.content } ).join(', '),
					removed : _.map(jsonModel.removed, function(obj) { return obj.content } ).join(', ')
				});
			});
		});

		this.jobPagesCollection.bind('reset', function(collection) {
			reviewedJobSitesCollection.reset();
			pendingJobSitesCollection.reset();

			_.each(collection.models, function(model) {
				(model.get('approvalStatus') == 'PENDING') ? pendingJobSitesCollection.add(model) : reviewedJobSitesCollection.add(model);
			});
		});
	},

	index : function() {
		if (!window.authenticatedOnInit) {
			this.navigate('login', true);
			return;
		}

		this.jobPagesCollection.fetch();

		$('#login-register-page').hide();
		$('#jobsites-page').show();
	},

	login : function() {
		$('#login-register-page').show();
		$('#jobsites-page').hide();

		this.jobPagesCollection.reset();
	}
});